import React, {useState, useEffect} from 'react';
import {Button, Divider, message, Table, Modal, Tag, Space, Drawer, Descriptions} from 'antd';
import {ColumnsType} from "antd/lib/table";
import {IPageResponse, IParam, statusEnum} from "@/common/common";
import {apiGetRoleList} from "@/apis/role";
import {ExclamationCircleOutlined, PlusOutlined, SyncOutlined} from "@ant-design/icons";
import ProTable from "@/components/ProTable";
import MenuForm from "@/pages/system/role/components/MenuForm";
import CreateRoleForm from "./components/CreateRoleForm";
import UpdateRoleForm from './components/UpdateRoleForm'
import {Role} from "@/pages/system/user/constant";

const {confirm} = Modal;

const TableList: React.FC<any> = () => {

  const [row, setRow] = useState<Role>();
  const [stepFormValues, setStepFormValues] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [stepMenuFormValues, setMenuStepFormValues] = useState({});

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [updateMenuModalVisible, handleUpdateMenuModalVisible] = useState<boolean>(false);

  const [loading, setLoading] = useState<boolean>(false);
  const [params, setParams] = useState<IParam>({page: 1, size: 10});
  const [pageResponse, setPageResponse] = useState<IPageResponse<any>>({pageInfo: {page: 1, size: 10, total: 0}})

  useEffect(() => {
    setLoading(true);
    apiGetRoleList(params, true).then(res => {
      setPageResponse(res);
    }).finally(() => setLoading(false));
  }, [params]);

  const columns: ColumnsType<any> = [
    {
      title: '角色名称',
      key: 'roleName',
      dataIndex: 'roleName',
      align: "center",
      render: (value, record) => {
        return <a onClick={() => setRow(record)}>{value}</a>;
      },
    },
    {
      title: '备注',
      key: 'remark',
      dataIndex: 'remark',
      align: "center",
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      align: "center",
      render: (value: string, record: any) => {
        const element = statusEnum[value]
        return element && <Tag color={element.color} key={record.id}>{element.text}</Tag>
      }
    },
    {
      title: '创建人',
      key: 'createBy',
      dataIndex: 'createBy',
      align: "center",
    },
    {
      title: '创建时间',
      key: 'createAt',
      dataIndex: 'createAt',
      align: "center",
    },
    {
      title: '更新人',
      key: 'updateBy',
      dataIndex: 'updateBy',
      align: "center",
    },
    {
      title: '更新时间',
      key: 'updateAt',
      dataIndex: 'updateAt',
      align: "center",
    },
    {
      title: '操作',
      key: 'option',
      dataIndex: 'option',
      align: "center",
      width: '250px',
      render: (text: any, record: any) => (
        <>
          <Button
            type="primary"
            size="small"
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </Button>
          <Divider type="vertical"/>
          <Button
            type="primary"
            size="small"
            onClick={() => {
              handleUpdateMenuModalVisible(true);
              setMenuStepFormValues(record);
            }}
          >
            分配菜单
          </Button>
          <Divider type="vertical"/>
          <Button
            type="primary"
            danger
            size="small"
            onClick={() => {
              showDeleteConfirm([record.id]);
            }}
          >
            删除
          </Button>
        </>
      )
    },
  ]

  const renderToolBar = () => (
    <Space size={10}>
      <Button type="primary" onClick={() => handleModalVisible(true)}>
        新增
      </Button>
      <Button>
        删除
      </Button>
      <Button type="dashed">
        <SyncOutlined/>
      </Button>
      {`共${pageResponse.pageInfo.total}条记录`}
    </Space>
  )

  const showDeleteConfirm = (ids: number[]) => {
    confirm({
      title: '是否删除记录?',
      icon: <ExclamationCircleOutlined/>,
      content: '删除的记录不能恢复,请确认!',
      onOk() {
        // handleRemoveOne(id).then((r) => {
        //   actionRef.current?.reloadAndRest?.();
        // });
      },
      onCancel() {
      },
    });
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: any, selectedRows: any) => {
      setSelectedRowKeys(keys);
    }
  };

  return (
    <ProTable
      pageResponse={pageResponse}
      columns={columns}
      loading={loading}
      rowSelection={rowSelection}
      scroll={{x: 1500}}
      toolBar={renderToolBar()}
    >

      <CreateRoleForm
        key={'CreateRoleForm'}
        onSubmit={async (value) => {
          // const success = await handleAdd(value);
          handleModalVisible(false);
          setStepFormValues({});
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        createModalVisible={createModalVisible}
      />

      <UpdateRoleForm
        key={'UpdateRoleForm'}
        onSubmit={async (value) => {
          // const success = await handleUpdate(value);
          handleUpdateModalVisible(false);
          setStepFormValues({});
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setStepFormValues({});
        }}
        updateModalVisible={updateModalVisible}
        currentData={stepFormValues}
      />

      <MenuForm
        onSubmit={async (value) => {
          // const success = await updateRoleMenu(value);
          handleUpdateMenuModalVisible(false);
          setMenuStepFormValues({});
        }}
        onCancel={() => {
          handleUpdateMenuModalVisible(false);
          setMenuStepFormValues({});
        }}
        updateMenuModalVisible={updateMenuModalVisible}
        currentData={stepMenuFormValues}
      />

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.id && (
          <Descriptions title="基本信息" bordered column={2} style={{margin: '20px 0 20px 20px', height: '400px'}}>
            {columns.map((item) => {
              return (
                <Descriptions.Item label={item.key}>
                  {item.key || ''}
                </Descriptions.Item>
              )
            })}
          </Descriptions>
        )}
      </Drawer>
    </ProTable>
  )
}

export default TableList
